<template>
  <div class="log-search-results-tab">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>组件错误日志</span>
          <span v-if="componentName" class="component-name-tag">
            <el-tag type="danger" size="small">{{ componentName }}</el-tag>
          </span>
          <span v-if="logLevel" class="level-name-tag">
            <el-tag type="warning" size="small">{{ logLevel }}</el-tag>
          </span>
        </div>
      </template>
      <div class="table-container">
        <el-table
          :data="logs"
          v-loading="loading"
          style="width: 100%"
          height="100%"
          stripe
          @row-click="viewLogFile"
        >
          <el-table-column prop="timestamp" label="时间" width="180">
            <template #default="{ row }">
              {{ formatTimestamp(row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="component" label="组件" width="120" />
          <el-table-column prop="level" label="级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getLevelType(row.level)" size="small">{{ row.level }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息" min-width="250" />
          <el-table-column prop="source_file" label="源文件" min-width="180" />
          <el-table-column prop="file_line" label="行号" width="80" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="viewLogFile(row)">查看文件</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :total="totalLogs"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 悬浮按钮 -->
    <div class="floating-button" @click="toggleFloatingViewer">
      <el-icon><Document /></el-icon>
      <span>日志查看器</span>
    </div>

    <!-- 悬浮日志查看器 -->
    <FloatingLogViewer 
      :is-open="isViewerOpen"
      :source-file="viewerLogDetails?.source_file"
      :highlight-line="viewerLogDetails?.file_line"
      :component-filter="viewerLogDetails?.component"
      :level-filter="viewerLogDetails?.level"
      @update:isOpen="val => isViewerOpen = val"
      @close="clearViewerLogDetails"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import * as api from '@/api'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import FloatingLogViewer from './FloatingLogViewer.vue' // 引入新的组件

const emits = defineEmits([])

interface LogEntry {
  timestamp: string
  component: string
  level: string
  message: string
  source_file?: string
  file_line?: number
}

interface Props {
  componentName?: string
  logLevel?: string
}

const props = defineProps<Props>()

const logs = ref<LogEntry[]>([])
const loading = ref(false)
const totalLogs = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 浮动日志查看器状态
const isViewerOpen = ref(false)
const viewerLogDetails = ref<LogEntry | null>(null)

// 获取日志级别类型 (与 ComponentsTab.vue 相同，可以考虑提取为公共工具函数)
const getLevelType = (level: string) => {
  switch (level.toLowerCase()) {
    case 'error': return 'danger'
    case 'warning': return 'warning'
    case 'info': return 'info'
    default: return 'info'
  }
}

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  try {
    return new Date(timestamp).toLocaleString()
  } catch {
    return timestamp // 如果解析失败，返回原始字符串
  }
}

const loadLogs = async () => {
  loading.value = true
  try {
    const response = await api.searchLogs(
      '', // 查询字符串为空
      props.componentName || '',
      props.logLevel || '',
      currentPage.value,
      pageSize.value
    )
    logs.value = response.logs || []
    totalLogs.value = response.total || 0
  } catch (error: any) {
    ElMessage.error(`加载日志失败: ${error.message || error}`)
    logs.value = []
    totalLogs.value = 0
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadLogs()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 切换每页大小时重置到第一页
  loadLogs()
}

watch([() => props.componentName, () => props.logLevel], () => {
  currentPage.value = 1 // 筛选条件变化时重置到第一页
  loadLogs()
})

onMounted(() => {
  loadLogs()
})

const toggleFloatingViewer = () => {
  isViewerOpen.value = !isViewerOpen.value
  if (isViewerOpen.value && !viewerLogDetails.value && logs.value.length > 0) {
    // 如果查看器打开，但没有选中日志，则默认显示第一个日志
    viewerLogDetails.value = logs.value[0]
  }
}

const clearViewerLogDetails = () => {
  viewerLogDetails.value = null
}

// 打开日志文件查看器
const viewLogFile = (log: LogEntry) => {
  if (log.source_file) {
    viewerLogDetails.value = { ...log, source_file: log.source_file, file_line: log.file_line }
    isViewerOpen.value = true
  } else {
    ElMessage.warning('该日志没有源文件信息')
  }
}

// 通过 ref 暴露组件方法给父组件
defineExpose({
  viewLogFile
})
</script>

<style scoped>
.log-search-results-tab {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative; /* 添加定位 */
}

.box-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: var(--color-heading);
}

.component-name-tag, .level-name-tag {
  margin-left: 8px;
}

.box-card :deep(.el-card__body) {
  flex: 1;
  padding: 0; /* 移除内边距，让表格完全填充 */
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  overflow: hidden;
}

.pagination-container {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  background-color: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-light);
}

/* 悬浮按钮样式 */
.floating-button {
  position: absolute;
  right: 20px;
  bottom: 80px;
  background: #409eff; /* Element UI Primary Blue */
  color: white;
  padding: 10px 15px;
  border-radius: 8px;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.floating-button:hover {
  background: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}
</style>